package com.toro.dao;


import com.toro.dao.Impl.UserDaoImpl;
import com.toro.domain.Group;
import com.toro.dao.Impl.GroupDaoImpl;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @ClassName: GroupSessionMemoryImpl
 * @Description:
 * @Author: ToroLHZ
 * @Date: 2023/12/11 17:42
 */
@Slf4j
public class GroupSessionMemoryImpl implements GroupSession {
    private static GroupDao groupDao = new GroupDaoImpl();
    private static UserDao userDao = new UserDaoImpl();

    private final Map<String, Group> groupMap = new ConcurrentHashMap<>();

    {
        getuserinfo();
    }

    /**
     * @Description: 创建一个聊天组
     * @Param: [groupName, members, creator]
     * @Return: Group
     * @Author: ToroLHZ
     * @Date: 2023/12/24 13:45
     **/
    @Override
    public void createGroup(String groupName, ArrayList<String> members, String creator) {
        ArrayList<Integer> membersList = new ArrayList<>();
        for (String member : members) {
            int userId = userDao.getUserIdByUsername(member);
            if (userId > 0) {
                membersList.add(userId);
            }
        }
        groupDao.createGroup(groupName, creator, membersList);
    }

    /**
     * @Description: 加入聊天组
     * @Param: [groupName, member]
     * @Return: com.toro.domain.Group
     * @Author: ToroLHZ
     * @Date: 2023/12/26 19:19
     **/
    @Override
    public Group joinMember(String groupName, String member) {
        int userId = userDao.getUserIdByUsername(member);
        int groupId = groupDao.getGroupIdByGroupName(groupName);
        boolean inGroup = groupDao.InGroupByGroupIdUserId(groupId, userId);
        if (inGroup) {
            Group group = groupDao.getGroupByGroupName(groupName);
            return group;
        }
        boolean b = groupDao.joinGroup(groupId, userId);
        if (b) {
            Group group = groupDao.getGroupByGroupName(groupName);
            return group;
        } else {
            return null;
        }
    }

    /**
     * @Description: 移除组成员
     * @Param: [name, member]
     * @Return: void
     * @Author: ToroLHZ
     * @Date: 2023/12/26 19:40
     **/
    @Override
    public void removeMember(String groupName, String member) {
        int userId = userDao.getUserIdByUsername(member);
        int groupId = groupDao.getGroupIdByGroupName(groupName);
        boolean inGroup = groupDao.InGroupByGroupIdUserId(groupId, userId);
        if (inGroup) {
            groupDao.deleteUserById(userId, groupId);
        }
    }

    @Override
    public Group removeGroup(String name) {
        return groupMap.remove(name);
    }

    /**
     * @Description: 获取组成员
     * @Param: [groupName]
     * @Return: java.util.List<java.lang.String>
     * @Author: ToroLHZ
     * @Date: 2023/12/24 16:49
     **/
    @Override
    public List<String> getMembers(String groupName) {
        List<String> members = new ArrayList<>();
        int groupId = groupDao.getGroupIdByGroupName(groupName);
        List<Integer> allMembers = groupDao.getAllMembers(groupId);
//        log.debug("allMembers:  {}", allMembers);
        for (Integer member : allMembers) {
            String userName = userDao.getUserNameByUserId(member);
            if (userName != null) {
                members.add(userName);
            }
        }
        return members;
    }

    /**
     * @Description: 获取组成员的 channel 集合, 只有在线的 channel 才会返回
     * @Param: [groupName]
     * @Return: java.util.List<io.netty.channel.Channel>
     * @Author: ToroLHZ
     * @Date: 2023/12/27 9:23
     **/
    @Override
    public List<Channel> getMembersChannel(String groupName) {
        List<String> members = getMembers(groupName);
        List<Channel> channelList = new ArrayList<>();
        Session session = SessionFactory.getSession();
        for (String member : members) {
            Channel channel = session.getChannel(member);
            if (channel != null) {
                channelList.add(channel);
            }

        }
        return channelList;
    }

    /**
     * @Description: 查看群是否存在，存在返回true,不存在返回false
     * @Param: [groupName]
     * @Return: boolean
     * @Author: ToroLHZ
     * @Date: 2023/12/24 15:40
     **/
    @Override
    public boolean EmptyGroup(String groupName) {
        int groupId = groupDao.getGroupIdByGroupName(groupName);
        return groupId > 0;
    }

    /**
     * 添加组信息
     * groupName/[m1,m2,m3,]
     *
     * @param group
     */
    public void setuserinfo(Group group) {
//        String filePath = "group.txt";
//        try {
//            FileWriter fileWriter = new FileWriter(filePath, true);
//            String groupName = group.getName();
//            Set<String> members = group.getMembers();
//            String groupinfo = groupName + "/[";
//            for (String member : members) {
//                groupinfo += member + ",";
//            }
//            groupinfo += "]";
//            fileWriter.write(groupinfo);
//            fileWriter.write("\r\n");
////            fileWriter.write(System.lineSeparator()); // 为了格式化输出，具体取决于你的系统
//            fileWriter.close();
////            System.out.println("Content has been appended to the file.");
//        } catch (IOException e) {
//            log.error(e.getMessage(), e);
//        }
    }

    /**
     * 获取组信息
     */
    public void getuserinfo() {
//        String filePath = "group.txt";
//        try {
//            FileReader fileReader = new FileReader(filePath);
//            BufferedReader bufferedReader = new BufferedReader(fileReader);
//            String line;
//            while ((line = bufferedReader.readLine()) != null) {
//                String[] split = line.split("/");
//                String groupName = split[0];
//                String[] split1 = split[1].substring(1, split[1].length() - 2).split(",");
//                Set<String> members = new HashSet<>();
//                for (String s : split1) {
//                    members.add(s);
//                }
//                Group group = new Group(groupName, members);
//                groupMap.putIfAbsent(groupName, group);
//            }
//            bufferedReader.close();
//        } catch (Exception e) {
//            log.error(e.getMessage(), e);
//        }

    }

}
